//
//  HWHomeInfoTopView.swift
//  HWanGame
//
//  Created by Apple on 2024/8/1.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import FSPagerView

class HWHomeInfoTopView: UIView,FSPagerViewDelegate,FSPagerViewDataSource {

    var banner = FSPagerView()
    var bannarModel: [HWHomeInfoBannerModel]? {
        didSet{
            self.pagerControl.numberOfPages = bannarModel?.count ?? 0
            banner.reloadData()
        }
    }
    // 懒加载滚动图片浏下标
    lazy var pagerControl:FSPageControl = {
        let pageControl = FSPageControl()
        //设置下标的个数
    //       pageControl.numberOfPages = 5
        //设置下标位置
        pageControl.contentHorizontalAlignment = .right
        //设置下标指示器边框颜色（选中状态和普通状态）
        pageControl.setStrokeColor(UIColor.color(hexString: "#D9D9D9",alpha:0.5), for: .normal)
        pageControl.setStrokeColor(UIColor.color(hexString: "#D9D9D9"), for: .selected)
        //设置下标指示器颜色（选中状态和普通状态）
        pageControl.setFillColor(UIColor.color(hexString: "#D9D9D9",alpha:0.5), for: .normal)
        pageControl.setFillColor(UIColor.color(hexString: "#D9D9D9"), for: .selected)
            
        //绘制下标指示器的形状 (roundedRect绘制绘制圆角或者圆形)
    //       pageControl.setPath(UIBezierPath.init(roundedRect: CGRect.init(x: 0, y: 8, width: 8, height: 5),cornerRadius: 4.0), for: .normal)
            
//        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 3*widthScale, height: 6*widthScale)), for: .normal)
//        pageControl.setPath(UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 6*widthScale, height: 6*widthScale)), for: .selected)
        return pageControl

    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(banner)
        addSubview(pagerControl)
        
        banner.dataSource = self
        banner.delegate = self
        banner.isInfinite = true
        banner.register(HWHomeInfoFSCell.self, forCellWithReuseIdentifier: "HWHomeInfoFSCell")
        banner.automaticSlidingInterval = 3
        banner.interitemSpacing = 9*widthScale
        banner.itemSize = CGSize(width: screenWidth, height: 170*widthScale)
        banner.removesInfiniteLoopForSingleItem = true
        
        banner.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        pagerControl.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-27*widthScale)
            make.bottom.equalToSuperview().offset(-24*widthScale)
            make.height.equalTo(4*widthScale)
            make.width.equalTo(100*widthScale)
        }
    }
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return bannarModel?.count ?? 0
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "HWHomeInfoFSCell", at: index) as! HWHomeInfoFSCell
        cell.model = bannarModel?[index]
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, willDisplay cell: FSPagerViewCell, forItemAt index: Int) {
            self.pagerControl.currentPage = index
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        let urlString = bannarModel?[index].link ?? ""
        if urlString.count > 0 {
            let webVC = XMGWebViewController()
            webVC.url = URL(string: urlString)
            HWUniversal.getCurrentVc().navigationController?.pushViewController(webVC, animated: true)
        }        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class HWHomeInfoFSCell:FSPagerViewCell {

    var bgImageView = UIImageView()

    
    var model:HWHomeInfoBannerModel? {
        didSet {
            guard let md = model else { return }
            bgImageView.sd_setImage(with: URL(string: md.image))
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.layer.shadowColor = UIColor.clear.cgColor
        
        addSubview(bgImageView)
        
        bgImageView.contentMode = .scaleAspectFill
        bgImageView.layer.cornerRadius = 8
        bgImageView.layer.masksToBounds = true
        
        bgImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(8*widthScale)
            make.leading.equalToSuperview().offset(12*widthScale)
            make.trailing.equalToSuperview().offset(-12*widthScale)
            make.height.equalTo(150*widthScale)
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


class HWHomeInfoTopCateView: UITableViewHeaderFooterView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
         
    private let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
    
    var model: [HWHomeInfoCateModel]? {
        didSet{
            guard let _ = model else { return }
            collectionView.reloadData()
        }
    }
    
    var updateCateData: ((_ cateID: Int) -> Void)?
    
    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        
        addSubview(collectionView)
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 15
        layout.minimumInteritemSpacing = 15
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets(top: 0, left: 12*widthScale, bottom: 0, right: 0)
        
        collectionView.collectionViewLayout = layout
        collectionView.backgroundColor = .clear
        collectionView.register(HWHomeInfoCateCell.self, forCellWithReuseIdentifier: HWHomeInfoCateCell.description())
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        model?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HWHomeInfoCateCell.description(), for: indexPath) as? HWHomeInfoCateCell else { return UICollectionViewCell() }
        cell.model = model?[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        var models = [HWHomeInfoCateModel]()
        model?.forEach { model in
            let itemModel = model
            itemModel.isSel = false
            models.append(itemModel)
        }
        models[indexPath.row].isSel = true
        let cateID = models[indexPath.row].id
        model = models
        updateCateData?(cateID)
        
        collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let name = model?[indexPath.row].name ?? ""
        let font = UIFont.systemFont(ofSize: 16*widthScale, weight: .medium)
        let attributedText = NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: font as Any])

        // 计算文本宽度
        let size = attributedText.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil).size
        let width = size.width
        
        return CGSize(width: width, height: 46.0*widthScale)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
}
